package cn.xaut.查找表;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

public class demo205 {

    // 巧妙方法 s.indexOf()
    public boolean isIsomorphic3(String s, String t) {
        
        if (s.length() != t.length())
            return false;

        char[] cs = s.toCharArray();
        char[] ts = t.toCharArray();
        
        for (int i = 0; i < s.length(); i++) {
            if (s.indexOf(cs[i]) != t.indexOf(ts[i]))
                return false;
        }
        return true;
    }
    
    // 用数组代替哈希映射
    public boolean isIsomorphic2(String s, String t) {
        int sLen = s.length();
        int tLen = t.length();

        if (sLen != tLen)
            return false;

        char[] cs = s.toCharArray();
        char[] ts = t.toCharArray();

        int[] a = new int[128];
        int[] b = new int[128];

        for (int i = 0; i < sLen; i++) {
            if (a[cs[i]] != b[ts[i]])
                return false;
            a[cs[i]] = i + 1;
            b[ts[i]] = i + 1;
        }
        
        return true;
    }
    
    // 哈希映射
    public boolean isIsomorphic(String s, String t) {

        int sLen = s.length();
        int tLen = t.length();
        
        if (sLen != tLen)
            return false;

        char[] cs = s.toCharArray();
        char[] ts = t.toCharArray();

        Map<Character, Integer> map1 = new HashMap<>();
        Map<Character, Integer> map2 = new HashMap<>();
        for (int i = 0; i < sLen; i++) {
            if (!Objects.equals(map1.put(cs[i], i), map2.put(ts[i], i)))
                return false;
        }
        
        return true;
    }

    public static void main(String[] args) {

        System.out.println(new demo205().isIsomorphic2("egg", "add"));//true
        System.out.println(new demo205().isIsomorphic2("foo", "bar"));//false
        System.out.println(new demo205().isIsomorphic2("paper", "title"));//true
        System.out.println(new demo205().isIsomorphic2("babc", "baba"));//false
        System.out.println(new demo205().isIsomorphic2("ab", "aa"));//false
    }
}
